#include <iostream>
#include <map>
#include <thread>
#include "mutex_lock.h"

using namespace std;

namespace {

class Stock {
public:
    Stock(string key_) : key(key_) {};

private:
    string key;
};

class StockFactory
{
 public:
  shared_ptr<Stock> get(const string& key)
  {
    shared_ptr<Stock> pStock;
    MutexLockGuard lock(mutex_);
    weak_ptr<Stock>& wkStock = stocks_[key];  // 如果 key 不存在，会默认构造一个
    pStock = wkStock.lock();  // 尝试把棉线提升为铁丝
    if (!pStock) {
      pStock.reset(new Stock(key));
      wkStock = pStock;  // 这里更新了 stocks_[key]，注意 wkStock 是个引用
    }
    return pStock; 
  }

 private:
  std::map<string, weak_ptr<Stock> > stocks_;
  mutable MutexLock mutex_;
};

void Handle() {
    auto fac = std::make_shared<StockFactory>();
    auto st = fac->get("test");

}

}

void HandleStock() {
    Handle();
}